package com.cx.common.mybatisplus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.cx.common.mybatisplus.handler.CreateUpdateTimeMetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author _
 * @date 2020/12/7
 * @see com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration
 */
@EnableTransactionManagement
@Slf4j
@Configuration
public class MybatisPlusConfig implements DisposableBean, ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    public static ApplicationContext getApplicationContext() {
        if (null == applicationContext) {
            throw new IllegalStateException("applicationContext is not set, please set bean in spring.");
        } else {
            return applicationContext;
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (null == MybatisPlusConfig.applicationContext) {
            MybatisPlusConfig.applicationContext = applicationContext;
        }
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public MetaObjectHandler createUpdateTimeMetaObjectHandler() {
        return new CreateUpdateTimeMetaObjectHandler();
    }

    @Override
    public void destroy() throws Exception {
        MybatisPlusConfig.applicationContext = null;
    }
}
